package com.ruoyi.rsikManage.MonitorPoint.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.rsikManage.MonitorPoint.domain.TMonitorPointRequest;
import com.ruoyi.rsikManage.domain.TUnitConfig;
import com.ruoyi.rsikManage.service.ITUnitConfigService;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.rsikManage.MonitorPoint.domain.TMonitorPoint;
import com.ruoyi.rsikManage.MonitorPoint.service.ITMonitorPointService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 设备Controller
 *
 * @author sxygsj
 * @date 2024-11-29
 */
@RestController
@RequestMapping("/riskManage/point")
public class TMonitorPointController extends BaseController
{

    private final ITMonitorPointService tMonitorPointService;
    private final TokenService tokenService;

    private final ITUnitConfigService iTUnitConfigService;

    public TMonitorPointController(ITMonitorPointService tMonitorPointService, TokenService tokenService,
                                   ITUnitConfigService iTUnitConfigService) {
        this.tMonitorPointService = tMonitorPointService;
        this.tokenService = tokenService;
        this.iTUnitConfigService = iTUnitConfigService;
    }

    /**
     * 查询设备列表
     */
   // @PreAuthorize("@ss.hasPermi('rsikManage:point:list')")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public TableDataInfo list(HttpServletRequest httpServletRequest,
                              @RequestBody(required = false) TMonitorPointRequest tMonitorPointRequest)
    {

        startPage(tMonitorPointRequest.getPageNum(),tMonitorPointRequest.getPageSize());
        // 获取当前登录用户的单位代码
        List<Long> unitCodes = tMonitorPointRequest.getUnitCodes();
        if (unitCodes == null || unitCodes.isEmpty()){

            if( httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null){
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            }
        }
        tMonitorPointRequest.setUnitCodes(unitCodes);
        List<TMonitorPoint> list = tMonitorPointService.selectTMonitorPointList(tMonitorPointRequest);
        return getDataTable(list);
    }


    /**
     * 查询设备列表
     */
    // @PreAuthorize("@ss.hasPermi('rsikManage:point:list')")
    @RequestMapping(value = "/list/group", method = {RequestMethod.GET, RequestMethod.POST})
    public TableDataInfo listGroup(HttpServletRequest httpServletRequest,
                              @RequestBody(required = false)  TMonitorPointRequest tMonitorPointRequest)
    {
        startPage(tMonitorPointRequest.getPageNum(),tMonitorPointRequest.getPageSize());
        // 获取当前登录用户的单位代码
        List<Long> unitCodes = tMonitorPointRequest.getUnitCodes();
        if (unitCodes == null || unitCodes.isEmpty()){

            if( httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null){
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            }
        }

        for (Long unit :unitCodes){
            List<Long> units= new ArrayList<>();
            units.add(unit);
            TMonitorPointRequest tMonitorPointRequest1 = new TMonitorPointRequest();
            tMonitorPointRequest1.setUnitCodes(units);
            List<TMonitorPoint> tMonitorPoints = tMonitorPointService.selectTMonitorPointList(tMonitorPointRequest1);
            TUnitConfig tUnitConfig = new TUnitConfig();
            tUnitConfig.setUnitCode(unit);
            List<TUnitConfig> tUnitConfigs = iTUnitConfigService.selectTUnitConfigList(tUnitConfig);
            TUnitConfig tUnitConfig1 = tUnitConfigs.get(0);

        }
        tMonitorPointRequest.setUnitCodes(unitCodes);
        List<TMonitorPoint> list = tMonitorPointService.selectTMonitorPointList(tMonitorPointRequest);
        return getDataTable(list);
    }

    /**
     * 导出设备列表
     */
   // @PreAuthorize("@ss.hasPermi('rsikManage:point:export')")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @RequestMapping(value = "/export", method = {RequestMethod.GET, RequestMethod.POST})
    public void export(HttpServletResponse response, @RequestBody TMonitorPointRequest tMonitorPointRequest)
    {
        List<TMonitorPoint> list = tMonitorPointService.selectTMonitorPointList(tMonitorPointRequest);
        ExcelUtil<TMonitorPoint> util = new ExcelUtil<>(TMonitorPoint.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取设备详细信息
     */
   // @PreAuthorize("@ss.hasPermi('rsikManage:point:query')")
    @RequestMapping(value = "/{apeId}", method = {RequestMethod.GET, RequestMethod.POST})

    public AjaxResult getInfo(@PathVariable("apeId") String apeId)
    {
        return success(tMonitorPointService.selectTMonitorPointByApeId(apeId));
    }

    /**
     * 新增设备
     */
   // @PreAuthorize("@ss.hasPermi('rsikManage:point:add')")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/insert", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult add(@RequestBody TMonitorPoint tMonitorPoint)
    {
        return toAjax(tMonitorPointService.insertTMonitorPoint(tMonitorPoint));
    }

    /**
     * 修改设备
     */
   // @PreAuthorize("@ss.hasPermi('rsikManage:point:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult edit(@RequestBody TMonitorPoint tMonitorPoint)
    {
        return toAjax(tMonitorPointService.updateTMonitorPoint(tMonitorPoint));
    }

    /**
     * 修改设备
     */
    // @PreAuthorize("@ss.hasPermi('rsikManage:point:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/batchUpdate", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult bathUpdate(@RequestBody List<TMonitorPoint> tMonitorPoints)
    {
        return toAjax(tMonitorPointService.batchUpdateTMonitorPoint(tMonitorPoints));
    }

    /**
     * 删除设备
     */
   // @PreAuthorize("@ss.hasPermi('rsikManage:point:remove')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
	@DeleteMapping("/{apeIds}")
    public AjaxResult remove(@PathVariable String[] apeIds)
    {
        return toAjax(tMonitorPointService.deleteTMonitorPointByApeIds(apeIds));
    }


    /**
     * 查询状态统计信息。
     *
     * 该接口用于根据请求参数查询并返回监控点的状态统计信息。统计信息包括总监控点数、在线监控点数和离线监控点数。
     * 如果请求体为空，则会自动使用当前登录用户的单位代码进行查询。
     *
     * @param httpServletRequest HTTP 请求对象，用于获取当前登录用户的单位代码。
     * @param tMonitorPointRequest 包含查询条件的请求对象（可选），可以包含以下字段：
     *                             - unitCodes: 单位代码列表（可选），用于筛选特定单位的监控点。
     *                             - unitCode: 单个单位代码（可选），用于筛选特定单位的监控点。
     *                             - 其他可能的查询条件（如时间范围、设备类型等）。
     * @return 返回一个包含监控点状态统计信息的 AjaxResult 对象，其中 data 字段为 HashMap，键值对如下：
     *         - "totalMonitorCount": 总监控点数
     *         - "onlineMonitorCount": 在线监控点数
     *         - "offlineMonitorCount": 离线监控点数
     *
     * 注意：如果既没有提供 `unitCodes` 也没有提供 `unitCode`，则默认使用当前登录用户的单位代码进行统计。
     */
// @PreAuthorize("@ss.hasPermi('rsikManage:point:status-count')")
    @RequestMapping(value = "/status-count", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getStatusCount(HttpServletRequest httpServletRequest,
                                     @RequestBody(required = false) TMonitorPointRequest tMonitorPointRequest)
    {
        // 初始化单位代码列表
        List<Long> unitCodes = new ArrayList<>();

        // 如果请求体不为空，则从请求体中获取单位代码
        if (tMonitorPointRequest != null) {
            unitCodes = tMonitorPointRequest.getUnitCodes();
        }

        // 如果单位代码列表为空，则尝试从当前登录用户获取单位代码
        if (unitCodes == null || unitCodes.isEmpty()) {
            if (httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null) {
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
                tMonitorPointRequest.setUnitCodes(unitCodes); // 更新请求对象中的单位代码
            }
        }

        // 调用服务层获取状态统计信息
        HashMap<String, Integer> statusCount = tMonitorPointService.getStatusCount(tMonitorPointRequest);

        // 返回结果
        return AjaxResult.success(statusCount);
    }


    // @PreAuthorize("@ss.hasPermi('rsikManage:point:status-count')")
    @RequestMapping(value = "/type-count", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getTypeCount(HttpServletRequest httpServletRequest,
                                     @RequestBody(required = false) TMonitorPointRequest tMonitorPointRequest)
    {
        // 初始化单位代码列表
        List<Long> unitCodes = new ArrayList<>();

        // 如果请求体不为空，则从请求体中获取单位代码
        if (tMonitorPointRequest != null) {
            unitCodes = tMonitorPointRequest.getUnitCodes();
        }

        // 如果单位代码列表为空，则尝试从当前登录用户获取单位代码
        if (unitCodes == null || unitCodes.isEmpty()) {
            if (httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null) {
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
                tMonitorPointRequest.setUnitCodes(unitCodes); // 更新请求对象中的单位代码
            }
        }

        // 调用服务层获取状态统计信息
        HashMap<String, Integer> statusCount = tMonitorPointService.getTypeCount(tMonitorPointRequest);

        // 返回结果
        return AjaxResult.success(statusCount);
    }
}
